
class CanvasImg{
    constructor(){

    }
    ImgColor=(imgurl,OldColor,NewColor,callBack)=>{
        try{
            let imgdata=new Image();
            imgdata.src=imgurl;
            let OldRGB=this.Str2RGB(OldColor);
            let newRGB=this.Str2RGB(NewColor);
            imgdata.onload=function(){
                let ConWidth=imgdata.width;
                let ConHeight=imgdata.height;
                const imgCanvas = document.createElement("canvas");
                imgCanvas.width = ConWidth;
                imgCanvas.height = ConHeight;
                let ctx=imgCanvas.getContext("2d");
                ctx.drawImage(imgdata,0,0);
                let ImageData=ctx.getImageData(0,0,imgCanvas.width,imgCanvas.height);
                for (let i=0;i<ImageData.data.length;i+=4)
                {
                    try{
                        if(ImageData.data[i]==OldRGB.r&&ImageData.data[i+1]==OldRGB.g&&ImageData.data[i+2]==OldRGB.b){
                            ImageData.data[i]=newRGB.r;
                            ImageData.data[i+1]=newRGB.g;
                            ImageData.data[i+2]=newRGB.b;
                            // ImageData.data[i+3]=255;
                        }
                    }catch (e) {
                        i=ImageData.data.length;
                    }

                }
                ctx.putImageData(ImageData,0,0);
                ctx.restore();
                let resdata = imgCanvas.toDataURL("image/png");
                if(typeof(callBack)=="function"){
                    callBack(resdata);
                }
            }
        }catch (e) {
            console.log("img change:",e)
            if(typeof(callBack)=="function"){
                callBack(imgurl);
            }
        }

    }

    //#FFFFFF
    Str2RGB=(ColorStr)=>{
        if(ColorStr.indexOf("#")==0&&ColorStr.length==7){
            let Rstr=ColorStr.substr(1,2);
            let Gstr=ColorStr.substr(3,2);
            let Bstr=ColorStr.substr(5,2);
            let Rnum=parseInt("0x"+Rstr);
            let Gnum=parseInt("0x"+Gstr);
            let Bnum=parseInt("0x"+Bstr);
            return {r:Rnum,g:Gnum,b:Bnum};
        }else {
            return undefined;
        }
    }
}module.exports=CanvasImg;